package com.example.itshome.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.itshome.R;
import com.example.itshome.manager.UserInfoManager;
import com.example.itshome.network.*;
import com.example.itshome.onclick.OnClickTurnTo;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.example.itshome.util.FileUtil.uriToFileApiQ;

public class SetPageActivity extends AppCompatActivity {


    private ImageView backImageView;
    private View changeHeaderLayout;
    private View changeNicknameLayout;
    private View changeIntroductionLayout;
    private View changePasswordLayout;
    private View joinUsLayout;
    private View logoutLayout;
    private Toast toast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_page);
        initFind();
        initButton();
        initToast();
    }

    private void initFind(){
        backImageView=findViewById(R.id.imv_set_page_back);
        changeHeaderLayout=findViewById(R.id.layout_set_page_change_header);
        changeNicknameLayout=findViewById(R.id.layout_set_page_change_nickname);
        changeIntroductionLayout=findViewById(R.id.layout_set_page_change_introduction);
        changePasswordLayout=findViewById(R.id.layout_set_page_change_password);
        joinUsLayout=findViewById(R.id.layout_set_page_join_us);
        logoutLayout=findViewById(R.id.layout_set_page_logout);
    }

    void initToast(){
        toast=new Toast(this);
    }

    private void initButton(){
        backImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        changeNicknameLayout.setOnClickListener(new OnClickTurnTo(SetPageActivity.this,ChangeNickNameActivity.class));
        changeIntroductionLayout.setOnClickListener(new OnClickTurnTo(SetPageActivity.this,ChangeIntroductionActivity.class));
        changePasswordLayout.setOnClickListener(new OnClickTurnTo(SetPageActivity.this,ChangePasswordActivity.class));
        joinUsLayout.setOnClickListener(new OnClickTurnTo(SetPageActivity.this,JoinUsActivity.class));
        changeHeaderLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(SetPageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(SetPageActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                } else {
                    //访问相册
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    //参数一:对应的数据的URI 参数二:使用该函数表示要查找文件的MIME类型
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, 1);
                }
            }
        });
        logoutLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder dialog=new AlertDialog.Builder(SetPageActivity.this);
                dialog.setTitle("提示")
                        .setMessage("确定要登出吗?")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                AbstractNetworkRequest request=new LogoutRequest(SetPageActivity.this)
                                        .setToast(toast);
                                request.start();
                            }
                        })
                        .setNegativeButton("取消",null);
                dialog.show();
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //参数一:对应的数据的URI 参数二:使用该函数表示要查找文件的MIME类型
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 1);
            } else {
                Toast.makeText(this, "你拒绝打开此权限，无法进行下一步操作！", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            //Log.i("TAG", "onActivityResult: " + selectedImage.toString());
            File file= uriToFileApiQ(selectedImage,this);

            Map<String,String> map=new HashMap<>();
            map.put("username", UserInfoManager.getInstance().getUser().getUsername());
            UploadFileRequest.uploadForm(map, "file", file, "file/upload-head", new Runnable() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            UserInfoManager.getInstance().initUser(SetPageActivity.this);
                        }
                    });
                }
            });

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}